package priv.mill.db;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;


public class MysqlWorker implements SqlWorker {

	private static Logger logger = Logger.getLogger(MysqlWorker.class);
	private String tableName;
	private String primary;
	private List<Map<String, Object>> desc;
	private String fields;

	
	public MysqlWorker(String tableName)  {
		try {
			this.tableName=tableName;
			List<Map<String, Object>> query = DBUtils.query("show index from "+tableName);
			for (Map<String, Object> map : query) {
				if(map.get("indexName").equals("PRIMARY")) {
					this.primary=map.get("columnName").toString();
					break;
				}
			}
			logger.info("主键为:"+primary);
			//{columnType=int(11), columnDefault=null, isNullable=NO, extra=auto_increment, columnKey=PRI, columnName=id}
			desc = DBUtils.query("desc "+tableName);
			StringBuilder fields = new StringBuilder();
			for (Map<String, Object> map : desc) {
				fields.append(map.get("columnName")+",");
			}
			this.fields=fields.substring(0, fields.length()-1);
			logger.info(desc);
		} catch (Exception e) {
			logger.error("表名不存在:"+tableName);
		}
	}

	@Override
	public String findById() throws SQLException {
		if(primary==null)throw new SQLException(tableName+":缺少主键");
		return String.format("SELECT %s FROM %s WHERE %s=?",fields, tableName,primary);
	}

	@Override
	public String findByPage() {
		return String.format("SELECT %s FROM %s LIMIT ?,?", fields,tableName);
	}

	@Override
	public int insert(Map<String, String> describe) throws SQLException, Exception {
		StringBuilder stringBuilder = new StringBuilder();
		List<Object> args= new ArrayList<>();
		for (Map<String, Object> map : desc) {
			if(!map.get("extra").equals("auto_increment")) {
				stringBuilder.append(map.get("columnName")+",");
				args.add(describe.get(NameUtils.under2Camel(map.get("columnName").toString())));
			}
		}
		String fields = stringBuilder.substring(0, stringBuilder.length()-1);
		String sql = String.format("INSERT INTO %s (%s) VALUES (%s)", tableName,
				fields,fields.replaceAll("[^,]+", "?"));
		return DBUtils.update(sql, args.toArray());
	}

	@Override
	public Integer update(Map<String, String> describe) throws SQLException, Exception {
		StringBuilder stringBuilder = new StringBuilder();
		List<Object> args= new ArrayList<>();
		for (Map<String, Object> map : desc) {
			if(!map.get("columnName").equals(primary)) {
				stringBuilder.append(map.get("columnName")+"=?,");
				args.add(describe.get(NameUtils.under2Camel(map.get("columnName").toString())));
			}
		}
		args.add(describe.get(NameUtils.under2Camel(primary)));
		String fields = stringBuilder.substring(0, stringBuilder.length()-1);
		String sql = String.format("UPDATE %s SET %s WHERE %s=?", tableName,
				fields,primary);
		return DBUtils.update(sql, args.toArray());
	}

	@Override
	public int getPrimary(Map<String, String> describe) {
		return Integer.parseInt(describe.get(primary));
	}

	@Override
	public String delete() {
		return String.format("DELETE FROM %s WHERE %s=?", tableName,primary);
	}

}
